package com.ken.common.event.plugins.msghandler.chain.impl;

import com.ken.common.event.apply.handle.EventHandler;
import com.ken.common.event.apply.handle.annotation.EventType;
import com.ken.common.event.plugins.msghandler.chain.AbstractMsgChain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * 运行模式的责任链
 */
@Component
@Order(10)
@Slf4j
public class RunModeChain extends AbstractMsgChain<EventHandler> {

    /**
     * 异步处理的线程池
     */
    @Autowired
    private Executor executor;

    @Override
    public void coreRun(ChainContext context, EventHandler eventHandler) {
        //获得方法上的注解
        EventType eventType = eventHandler.getClass().getAnnotation(EventType.class);

        //构建线程体
        Runnable runnable = () -> {
            //执行责任链下一步
            super.nextInvoce(context, eventHandler);
        };

        //查看运行类型
        if (!eventType.isAsync()) {
            //如果是非异步执行
            runnable.run();
        } else {
            //如果是异步执行,则放入线程池
            executor.execute(runnable);
        }
    }
}
